package com.cs.controller;

import com.cs.pojo.*;
import com.cs.resultVO.ResultVO;
import com.cs.service.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping ("/drugpeople")
@ResponseBody
public class DrugPeopleController {
    
    @Resource
    private DrugPeopleService drugPeopleService;
    @Resource
    private BeHospitalService beHospitalService;
    @Resource
    private DrugService drugService;
    @Resource
    private ChargeprojectService chargeprojectService;
    @Resource
    private PricepeopleService pricepeopleService;
    @Resource
    private PeopleService peopleServicel;
    
    /**
     * 开药操作
     */
    @RequestMapping(value = "assignDrug" , method = RequestMethod.POST)
    public ResultVO<Drugpeople> assignDrug(Drugpeople d){
        // 开药前提
        Behospital behospital = beHospitalService.queryById(d.getBehId());
        if (behospital == null) {
            return new ResultVO<>(500,"请联系前台是否登记");
        }
    
        /**
         * 开药条件：
         *      1. 一个病人可开多个药，且不能重复开相同的药
         */
        
        // 逻辑处理
        // 开药条件1
        List<Drugpeople> drugpeopleList = drugPeopleService.queryByType(d.getBehId() , false);
        if (!drugpeopleList.isEmpty()){
            for (Drugpeople drugpeople : drugpeopleList) {
                if (drugpeople.getDrId() == d.getDrId()) {
                    return new ResultVO<>(500,"不能选用重复的药！");
                }
            }
        }
    
        Drugpeople drugpeople = new Drugpeople();
        drugpeople.setDrId(d.getDrId());
        drugpeople.setBehId(d.getBehId());
        drugpeople.setDrNumber(d.getAssignDrugNum());
        drugpeople.setBehName(d.getBehName());
        drugpeople.setDrOknumber(0);
        int add = drugPeopleService.add(drugpeople);
        if (add < 0) {
            return new ResultVO<>(500,"服务器异常！");
        }
        return new ResultVO<>();
    }
    
    
    /**
     * 病人详细
     * @param behId
     * @return
     */
    @RequestMapping(value = "peopleInfo" , method = RequestMethod.GET)
    public ResultVO<Drugpeople> peopleInfo(Integer behId){
    
        // 数据填充 （选择最多项进行遍历 中间表）
        // 病人表：姓名
        // 药物表：药品名称
        // 中间表：病人号 药品数量 已发数量 未发数量
        List<Drugpeople> drugPeopleList = drugPeopleService.queryByType(behId , false);
        if (drugPeopleList.isEmpty()){
            return new ResultVO<>(500,"请为该病人进行药物分配!");
        }
        List<Drugpeople> list = new ArrayList<>();
        for (Drugpeople d : drugPeopleList) {
            // 药物信息填充
            Drug drug = drugService.queryById(d.getDrId());
            d.setDrName(drug.getDrId()+" - "+drug.getDrName());
            if (d.getDrNumber()-d.getDrOknumber() >= 0){
                d.setNotSentDrugNum(d.getDrNumber()-d.getDrOknumber());
            }else{
                return new ResultVO<>(500,"数据异常请联系管理员！");
            }
            // 病人名称填充
            People people = peopleServicel.queryById(behId);
            d.setBehName(people.getBehName());
            list.add(d);
        }
        
        return new ResultVO<>(list);
    }

    /**
     * 发药操作
     * @param d
     * @return
     */
    @RequestMapping(value = "sendDrug" , method = RequestMethod.GET)
    public ResultVO<Drugpeople> sendDrug(Drugpeople d){
        
        System.out.println("d : " + d);
        
        // 中间表查信息
        List<Drugpeople> droppedList = drugPeopleService.queryByType(d.getBehId() , false);
        if (droppedList.isEmpty()) {
            return new ResultVO<>(500,"请联系前台是否登记信息！");
        }
        Drugpeople drugpeople = null;
        for (Drugpeople tmp : droppedList) {
            if (tmp.getDrId() == d.getDrId()){
                drugpeople = tmp;
                break;
            }
        }
        if (drugpeople == null) {
            return new ResultVO<>(500,"该病人未分配指定药物！");
        }

        /**
         * 取药前提：
         *      1. 是否发完指定分配药
         *      2. 库存有药
         *      3. 已付钱，且大于或等于药物预算值 (付完满额)
         *      4. 按药分配（不能超过预算值）
         */
        
        // 数据逻辑处理
        
        // 发药条件1（是否发完指定分配药）
        if (drugpeople.getDrNumber() == drugpeople.getDrOknumber()){
            return new ResultVO<>(500,"药物已发完指定量！");
        }
        
        int waitSendDrug = drugpeople.getDrNumber() - drugpeople.getDrOknumber();
        int sendDrug = d.getSendDrNumber() == null? waitSendDrug:d.getSendDrNumber();
        
        // 发药条件2 (仓库库存是否到达指定药量)
        Drug drug  = drugService.queryById(drugpeople.getDrId());
        if (drug == null) {
            return new ResultVO<>(500,"指定的药物不存在！");
        }
        if (drug.getDrNumber() < sendDrug){
            return new ResultVO<>(500,"药物库存不足！");
        }
        
        // 发药条件3 (付钱 不能少于 药物指定量的价钱)
        // 中间表查询 指定用户
        List<Pricepeople> pricePeopleList = pricepeopleService.queryById(d.getBehId() , false);
        // 每个名称有对应的一个清单支付
        Pricepeople pricepeople = pricePeopleList.get(0);
        // 查支付的钱
        Chargeproject chargeproject = chargeprojectService.queryById(pricepeople.getChapId());
        if (chargeproject == null) {
            return new ResultVO<>(500,"服务器异常请联系前台！");
        }
        // 最终条件判断 付钱 + 住院押金 >= （药物单价1 * 药物量1）+（药物单价2 * 药物量2）+...
        Behospital behospital = beHospitalService.queryById(d.getBehId());
        BigDecimal num = new BigDecimal(0);
        for (Drugpeople tmp : droppedList) {
            Drug tmpDrug = drugService.queryById(tmp.getDrId());
            num = num.add(tmpDrug.getDrOutprice().multiply(new BigDecimal(tmp.getDrNumber())));
        }
        int resultValue = (chargeproject.getChapMoney().add(behospital.getBehAntecedent())).compareTo(num);
        if (resultValue < 0){
            return new ResultVO<>(500,"请到付钱窗口审核账单！");
        }
        
        // 发药条件3（不能超过计划量）
        // 满足以上条件发药执行
        if (waitSendDrug >= sendDrug){
            // 发药量 添加 （ok添加）
            drugpeople.setDrOknumber(drugpeople.getDrOknumber() + sendDrug);
            
            //修改库信息
            int update = drugPeopleService.update(drugpeople);
            if (update <= 0){
                return new ResultVO<>(500,"提交失败");
            }
        }else{
            return new ResultVO<>(500,"请控制预计药量进行发药!");
        }
        return new ResultVO<>();
    }
    
    
    /**
     * 批量发药操作
     * @param d
     * @return
     */
    @RequestMapping(value = "slapSendDrugs" , method = RequestMethod.POST)
    public ResultVO<Drugpeople> sendDrugs(Drugpeople d){
    
        System.out.println("d : " + d);
        
        Integer drId = d.getDrId();
        Integer assignDrugNum = d.getAssignDrugNum();
        String[] behIds = d.getBehIds();
        
        if (drId == null || assignDrugNum == null || behIds == null){
            return new ResultVO<>(500,"传递参数有误请联系管理员！");
        }
    
    
        /**
         * 开药条件：
         *      1. 住院病人有效
         *      2. 一个病人可开多个药，且不能重复开相同的药
         */
        
        Behospital behospital;
        List<Object> str = new ArrayList<>();
        List<Object> str2 = new ArrayList<>();
        for (String behId : behIds) {
            
            // 条件1
            behospital = beHospitalService.queryById(Integer.parseInt(behId));
            if (behospital == null) {
                str.add(behId);
            }
            
            // 条件2
            List<Drugpeople> drugpeopleList = drugPeopleService.queryByType(Integer.parseInt(behId) , false);
            if (!drugpeopleList.isEmpty()){
                for (Drugpeople drugpeople : drugpeopleList) {
                    if (drugpeople.getDrId() == drId) {
                        str2.add(behId);
                    }
                }
            }
            
        }
        if (str.size() > 0){
            return new ResultVO<>(500,"病人Id："+str+" 号 请联系前台是否登记!");
        }
        if (str2.size() > 0){
            return new ResultVO<>(500,"病人Id："+str2+" 号 不能选用重复的药！");
        }
    
        
        // 开药操作
        for (String behId : behIds) {
            
            Drugpeople drugpeople = new Drugpeople();
            drugpeople.setDrId(drId);
            drugpeople.setBehId(Integer.parseInt(behId));
            drugpeople.setDrNumber(assignDrugNum);
            drugpeople.setDrOknumber(0);
            int add = drugPeopleService.add(drugpeople);
            if (add < 0) {
                return new ResultVO<>(500,"服务器异常！");
            }
        }
        
        return new ResultVO<>();
    }
    
}
